#include <QDebug>
#include <QCoreApplication>
#include <QTimer>
#include <QProcess>
#include "dbus-monitor.h"

#define DBUS_INF "org.freedesktop.DBus"
#define DBUS_PATH "/org/freedesktop/DBus"
#define DBUS_SVC DBUS_INF

#define NET_DBUS_INF "org.freedesktop.NetworkManager"
#define NET_DBUS_PATH "/org/freedesktop/NetworkManager"



int main(int argc, char *argv[])
{
    qputenv("DISPLAY", ":0");
    QCoreApplication app(argc, argv);
    QString matchStr = "path=%1, interface=%2, type=%3, member=%4";
    DBusMonitor *dbm = new DBusMonitor  (DBUS_BUS_SYSTEM);
    dbm->create_and_init_connection();
    dbm->add_rule(matchStr.arg(NET_DBUS_PATH).
                          arg(NET_DBUS_INF).
                          arg("signal").
                          arg("PropertiesChanged"));

    dbm->add_handler(DBusMonitor::default_handler);

    dbm->start();

    DBusMonitor *dbm2 = new DBusMonitor(DBUS_BUS_SESSION);
    dbm2->create_and_init_connection();
    dbm2->add_handler(DBusMonitor::default_handler);
    dbm2->add_rules({"path=/org/gnome/SettingsDaemon/Rfkill",
                     "path=/StatusNotifierItem"});
    dbm2->start();
    QProcess p;
    p.start("fcitx-remote -a");
    p.waitForFinished();
    QString addr(p.readAllStandardOutput());
    qDebug() << addr << addr.trimmed();
    DBusMonitor dbm3(addr.trimmed());
    qDebug() << dbm3.create_and_init_connection();
    dbm3.add_handler(DBusMonitor::default_handler, &dbm3);
    dbm3.add_rule("interface=org.fcitx.Fcitx.InputContext");
    dbm3.start();
    QObject::connect(&dbm3, &DBusMonitor::connectionLost, [&dbm3](){
       qDebug() << "DBus connection Lost!";
       dbm3.stop();
       dbm3.wait();
    });
    QTimer::singleShot(30000, [&app, dbm, dbm2]() {
        dbm->stop(); dbm2->stop();
        dbm->wait();
        dbm2->wait();
        delete dbm2;
        delete dbm;
        qDebug() << "Connection Stopped";

    });
    app.exec();


}
